﻿using czj_shop.Models.Database;
using czj_shop.Models.Good;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace czj_shop.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class GoodController : ControllerBase
    {
        public GoodController(czj_shopContext db)
        {
            _db = db;
        }
        private readonly czj_shopContext _db;
        /// <summary>
        /// 构造函数 
        /// </summary>
        /// <param name = "db" ></ param >

        //后台商品管理

        /// < summary >
        /// 商品新增接口
        /// </ summary >
        /// < param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public string AddGood(AddGoodRequest request)
        {
            //实现
            //类的转换 自定义请求类 转换成数据库模型类
            var good = new Good
            {
                Name = request.Name,
                Pic = request.Pic,
                Desciption = request.Desciption,
                Tid = request.Tid,
                Createtime = DateTime.Now,
                Price = request.Price,
                Status = request.Status,
                Quantity = request.Quantity
            };

            _db.Goods.Add(good);
            var row = _db.SaveChanges();
            if (row > 0)
                return "新增成功";
            return "新增失败";
        }
        /// <summary>
        /// 商品修改接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string UpdateGood(UpdateGoodRequest request)
        {
            var good = _db.Goods.FirstOrDefault(x => x.Id == request.Id);
            if (good == null)
                return "商品不存在";

            //类的转换 自定义类 转换成数据库模型类
            good.Name = request.Name;
            good.Price = request.Price;
            good.Tid = request.Tid;
            good.Desciption = request.Desciption;
            good.Pic = request.Pic;
            good.Quantity = request.Quantity;

            //类的转换 AOTOMAP 工具类 作用 把两个类里面的属性去进行映射赋值

            _db.Goods.Update(good);
            var row = _db.SaveChanges();
            if (row > 0)
                return "修改成功";
            return "修改失败";
        }
        /// <summary>
        /// 商品查询接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public List<Good> GetGoodList(GetGoodListRequest request)
        {
            //条件动态的 待执行状态 
            var goodDB = _db.Goods.AsQueryable();
            if (!string.IsNullOrEmpty(request.Keyword))
                goodDB = goodDB.Where(x => x.Name.Contains(request.Keyword));

            var goodList = goodDB
                 .OrderByDescending(x => x.Id)
                 //分页 先跳过前N个 取多少个
                 .Skip((request.PageIndex - 1) * request.PageSize)
                 .Take(request.PageSize)
                 //在ToList之前都是在组建SQL过程
                 //之后执行SQL
                 .ToList();
            return goodList;
        }

        /// <summary>
        /// 商品删除接口
        /// </summary>
        /// <param name="goodId"></param>
        /// <returns></returns>
        [HttpPost]
        public string DeleteGood(int goodId)
        {
            var good = _db.Goods.FirstOrDefault(x => x.Id == goodId);
            if (good == null)
                return "商品不存在";

            _db.Goods.Remove(good);
            var row = _db.SaveChanges();
            if (row > 0)
                return "删除成功";
            return "删除失败";
        }
        //        后台商品分类管理
        //分类新增接口

        /// <summary>
        /// 新增商品分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string AddCategory(AddCateRequest request)
        {
            var cate = new Cate
            {
                Name = request.Name
            };

            _db.Cates.Add(cate);
            var row = _db.SaveChanges();

            if (row > 0)
                return "新增成功";
            return "新增失败";
        }
        /// <summary>
        /// 分类修改接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string UpdateCategory(UpdateCateRequest request)
        {
            var cate = _db.Cates.FirstOrDefault(x => x.Id == request.Id);

            if (cate == null)
                return "分类不存在";

            cate.Name = request.Name;
            _db.Cates.Update(cate);
            var row = _db.SaveChanges();
            if (row > 0)
                return "更新成功";
            return "更新失败";
        }
        /// <summary>
        /// 分类查询接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public List<Cate> GetCategoryList(GetCateListRequest request)
        {
            var cateDb = _db.Cates.AsQueryable();

            if (!string.IsNullOrEmpty(request.Keyword))
                cateDb = cateDb.Where(x => x.Name.Contains(request.Keyword));

            var cateList = cateDb.OrderByDescending(x => x.Id)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToList();
            return cateList;
        }

        /// <summary>
        /// 分类删除接口
        /// </summary>
        /// <param name="cateId"></param>
        /// <returns></returns>
        [HttpPost]
        public string DeleteCategory(int cateId)
        {
            var category = _db.Cates.FirstOrDefault(x => x.Id == cateId);
            if (category == null)
                return "分类不存在";

            _db.Cates.Remove(category);

            var row = _db.SaveChanges();
            if (row > 0)
                return "删除成功";
            return "删除失败";
        }
        //前端商品分类列表接口（列出商品分类数据） 输入：无 输出：商品分类列表（分类名称、分类Id）
        /// <summary>
        /// 前端商品分类列表接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<Cate> GetCates()
        {
            return _db.Cates.ToList();
        }

        //前端商品列表接口 输入：商品分类Id,搜索关键字，分页数据 输出：商品列表（商品名称，商品Id，商品图片），总数
        /// <summary>
        /// 前端商品列表接口
        /// </summary>
        /// <param name="reqeust"></param>
        /// <returns></returns>
        [HttpPost]
        public GetGoodsResponse GetGoods(GetGoodsRequest reqeust)
        {
            //实现
            var goodDb = _db.Goods.AsQueryable();

            if (!string.IsNullOrEmpty(reqeust.Keyword))
                goodDb = goodDb.Where(x => x.Name.Contains(reqeust.Keyword));

            if (reqeust.CateId > 0)
                goodDb = goodDb.Where(x => x.Id == reqeust.CateId);

            var total = goodDb.Count();

            var goodList = goodDb
                //构建一个新的列表
                .Select(x => new GoodModel
                {
                    GoodPic = x.Pic,
                    GoodId = x.Id,
                    GoodName = x.Name
                })
                .OrderByDescending(x => x.GoodId)
                .Skip((reqeust.PageIndex - 1) * reqeust.PageSize)
                .Take(reqeust.PageSize)
                .ToList();

            var response = new GetGoodsResponse
            {
                GoodList = goodList,
                //不分页的总数 前端需要用这个来判断还有没有数据需要加载
                Total = total
            };
            return response;
        }
        //前端商品详情接口 输入：商品Id 输出：商品标题，图片，价格，库存，描述
        /// <summary>
        /// 商品Id
        /// </summary>
        /// <param name="goodId"></param>
        /// <returns></returns>
        [HttpPost]
        public GetGoodDetailResponse GetGoodDetail(int goodId)
        {
            var good = _db.Goods.FirstOrDefault(x => x.Id == goodId);
            if (good == null)
                return null;

            return new GetGoodDetailResponse
            {
                GoodPic = good.Pic,
                GoodName = good.Name,
                Desciption = good.Desciption,
                Price = good.Price,
                Quantity = good.Quantity
            };
        }
    }


}
